﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages.User.Setting
{
    using Filters;
    using System.ComponentModel.DataAnnotations;

    [OwnPage]
    public class ChangePwdModel : PageModel
    {
        private readonly UserService _userService;
        public ChangePwdModel(UserService userService)
        {
            _userService = userService;
        }

        [BindProperty]
        [Display(Name = "旧密码")]
        [Required(ErrorMessage = "{0}是必填项")]
        public string OldPassword { get; set; }

        [BindProperty]
        [Display(Name = "新密码")]
        [Required(ErrorMessage = "{0}是必填项"), StringLength(25, ErrorMessage = "{0}必须在 {2}-{1} 个字符", MinimumLength = 8)]
        public string NewPassword { get; set; }

        [BindProperty]
        [Display(Name = "确认密码")]
        [Compare("NewPassword", ErrorMessage = "两次密码不一致")]
        public string ConfirmPassword { get; set; }

        public IActionResult OnGetAsync()
        {
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "表单验证有错误");
                return Page();
            }

            try
            {
                await _userService.ChangePasswordAsync(User.Identity.UserId(), this.OldPassword, this.NewPassword);

                ViewData["Success"] = true;
                return Page();
            }
            catch (Exception ex)
            {
                return RedirectToPage("/Error", new { message = ex.Message });
            }
        }
    }
}